package libra;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.spring.convert.converter.config.DefaultNacosConfigConverter;

import libra.init.Config;

/**
 * 基于Nacos提供的ConfigService注入，实现手动编程的应用方式
 */
@RestController
@RequestMapping("manual")
public class ManualController {
	private String msg;
	private String refresh;
	private Double version;
	
	@NacosInjected
	private ConfigService configService;
	
	@PostConstruct
	public void init() throws Exception{
		// 手动调用DefaultNacosConfigConverter进行配置文件的内容解析
		DefaultNacosConfigConverter<Map> defaultNacosConfigConverter = 
				new DefaultNacosConfigConverter<>(Map.class, new DefaultFormattingConversionService(), "json");
		// 通过getConfigAndSignListener()在获取配置文件的同时，为其添加Listener监听器。等价于getConfig() + addListener()
		// 需要注意此时设置的timeout，仅针对GetConfig()获取配置。不同于@NacosConfigListener(timeout)，其不存在Converter转换耗时
		String configAndSignListener = configService.getConfigAndSignListener(Config.dataId, "DEFAULT_GROUP", 3000, new Listener() {
			@Override
			public void receiveConfigInfo(String configInfo) {
				// !!!：DefaultNacosConfigConverter解析处理返回的Map，KV均是String类型，需要手动转换数值类型
				Map convert = defaultNacosConfigConverter.convert(configInfo);
				msg = (String) convert.get("msg");
				version = Double.valueOf( (String)convert.get("version") );
				refresh = (String) convert.get("refresh");
				System.out.println( "ManualController.Listener触发。"+ Config.dataId + "最新内容：\r\n" + convert );
			}
			@Override
			public Executor getExecutor() {
				return null;
			}
		});
		// !!!：DefaultNacosConfigConverter解析处理返回的Map，KV均是String类型，需要手动转换数值类型
		Map convert = defaultNacosConfigConverter.convert(configAndSignListener);
		msg = (String) convert.get("msg");
		version = Double.valueOf( (String)convert.get("version") );
		refresh = (String) convert.get("refresh");
		System.out.println( "ManualController.启动初始化获取配置。"+ Config.dataId + "初始内容：\r\n" + convert );
	}
	
	@RequestMapping("getData")
	public Object getDate(HttpServletRequest req, HttpServletResponse resp) {
		return new HashMap<>() {{
			put("resp_msg", msg);
			put("resp_refresh", refresh);
			put("resp_version", version);
		}};
	}
}
